/*
 * This file is here just so I can debug my own code. Use it if you will, but
 * you should generally just ignore it.
 */

package qicky;

import com.dkasza.qicky.HttpRequestHandler;
import com.dkasza.qicky.Xml;
import com.dkasza.qicky.HttpStaticRequestHandler;
import com.dkasza.qicky.HttpServer;
import com.dkasza.qicky.Xml.*;
import com.dkasza.qicky.Http.Request;
import com.dkasza.qicky.Http.Response;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author Dániel
 */
public class Quicky {
    public static void main(String[] args) throws IOException{
        HttpServer myServer = new HttpServer(80);
        
        HttpRequestHandler quickyWall = new HttpRequestHandler() {

            @Override
            public String prefix() {
                return "/wall";
            }

            class Post {
                public Post(String n, String m) {
                    name = n; msg = m;
                }
                public String name; public String msg;
            }
            
            ArrayList<Post> posts = new ArrayList<>();
            
            @Override
            public Response handler(Request request) {
                Template template = Template.fromFile("c:\\QuickyWall\\wall.html");                
                try {
                    String name = Xml.escape(request.postData("name").stringValue);
                    String msg  = Xml.escape(request.postData("msg").stringValue);
                    template.subs("name", name);
                    posts.add(new Post(name, msg));
                } catch (Request.KeyNotFoundException e) {}
                String msgs = "";
                for(int i = 0; i < posts.size(); i++) {
                    Post current = posts.get(i);
                    msgs += "<h1>"+current.name.replace("\n", "") +"</h1>"
                          + "<p>" +current.msg +"</p>\n";
                }
                template.subs("posts", msgs);
                template.subs("posts", msgs);
                String content = template.render("");
                return new Response(true, request.messages.headerOK 
                        + request.messages.headerContentLength(content)
                        + request.messages.headerContentType()
                        + "\n" + content);
            }
        };
        myServer.addRequestHandler(quickyWall);
        myServer.addRequestHandler(new HttpStaticRequestHandler("/", "c:\\www", "/index.html"));
        myServer.start();
    }
}
